import mountElement from './mountElement';
import updateTextNode from './updateTextNode';
import updateNodeElement from './updateNodeElement';
import createDOMElement from './createDOMElement';
import unmountNode from './unmountNode';
import diffComponent from './diffComponent';
export default function diff(
  virtualDOM,
  container,
  oldDOM = container.firstChild
) {
  // 旧的虚拟DOM，也就是挂载在 oldDOM 元素上的_virtualDOM
  const oldVirtualDOM = oldDOM && oldDOM._virtualDOM;
  // 旧的组件实例对象
  const oldComponent = oldVirtualDOM && oldVirtualDOM.component;
  // 判断 oldDOM 是否存在
  if (!oldDOM) {
    mountElement(virtualDOM, container);
  } else if (
    virtualDOM.type !== oldVirtualDOM.type &&
    typeof virtualDOM.type !== 'function'
  ) {
    const newElement = createDOMElement(virtualDOM);
    oldDOM.parentNode.replaceChild(newElement, oldDOM);
  } else if (typeof virtualDOM.type === 'function') {
    // 组件
    diffComponent(virtualDOM, oldComponent, oldDOM, container);
  } else if (oldVirtualDOM && virtualDOM.type === oldVirtualDOM.type) {
    if (virtualDOM.type === 'text') {
      // 更新内容
      updateTextNode(virtualDOM, oldVirtualDOM, oldDOM);
    } else {
      // 更新元素属性
      // oldDOM 旧的DOM元素，virtualDOM 更新后的虚拟DOM，oldVirtualDOM 旧的虚拟DOM
      updateNodeElement(oldDOM, virtualDOM, oldVirtualDOM);
    }
    // 遍历 virtualDOM 子元素，进行对比
    virtualDOM.children.forEach((child, i) => {
      // child 更新后的虚拟DOM
      // oldDOM 父级 DOM 元素，也就是子元素的容器
      // oldDOM.childNodes[i] 旧的 DOM 元素
      diff(child, oldDOM, oldDOM.childNodes[i]);
    });

    // 删除节点
    // 获取旧节点
    let oldChildNodes = oldDOM.childNodes;
    if (oldChildNodes.length > virtualDOM.children.length) {
      for (
        let i = oldChildNodes.length - 1;
        i > virtualDOM.children.length - 1;
        i--
      ) {
        unmountNode(oldChildNodes[i]);
      }
    }
  }
}
